const express = require("express");
const cors = require("cors");
const axios = require("axios");
const fs = require("fs");
const path = require("path");
const unzipper = require("unzipper");
const router = express.Router();
const { exec } = require("child_process");
// 获取系统盘符列表、Node.js版本和当前Node.js路径
const os = require("os");

router.get("/", function (req, res) {
  // eslint-disable-next-line no-path-concat
  res.sendFile(__dirname + "/index.html");
});
const pcInfo = {
  osNum: 64,
  osType: "Windows",
  currentNodeVersion: "16.17.0",
};
router.get("/getInfo", (req, res) => {
  // 清除系统环境变量缓存
  // 清除系统环境变量缓存
  exec('setx PATH ""', (error, stdout, stderr) => {
    if (error) {
      console.error(`清除系统环境变量缓存出错: ${error.message}`);
      return;
    }

    console.log("系统环境变量缓存已清除");

    // 获取系统盘符
    exec("wmic logicaldisk get caption", (error, stdout, stderr) => {
      if (error) {
        console.error(`获取系统盘符出错: ${error.message}`);
        return;
      }

      const driveLetters = stdout
        .split(/\s*\n\s*/)
        .map((line) => line.trim())
        .filter(Boolean)
        .filter((drive) => /^[A-Za-z]:$/.test(drive));

      const systemArch = os.arch().includes("64") ? "64" : "32"; // 获取操作系统位数

      let osType;
      switch (os.platform()) {
        case "win32":
          osType = "Windows";
          break;
        case "linux":
          osType = "Linux";
          break;
        case "darwin":
          osType = "Mac";
          break;
        default:
          osType = "Unknown";
      }

      console.log("系统盘符列表:", driveLetters);
      console.log("操作系统位数:", systemArch);
      console.log("操作系统类型:", osType);

      if (osType === "Linux" || osType === "Mac") {
        res.json({ message: "不支持 Linux 和 Mac 操作系统" });
        return;
      }

      // 获取 Node.js 版本信息
      exec("node -v", (error, stdout, stderr) => {
        if (error) {
          console.error(`获取Node.js版本出错: ${error.message}`);
          return;
        }

        const nodeVersion = stdout.trim().replace(/^v/, "");

        const pcInfo = {
          osNum: systemArch || 64,
          osType: osType || "Windows",
          currentNodeVersion: nodeVersion,
        };

        res.send({
          系统盘符列表: driveLetters,
          操作系统位数: systemArch,
          操作系统类型: osType,
          nodeVersion,
        });
      });
    });
  });
});

function getNodeVersion(retryCount = 3) {
  return new Promise((resolve, reject) => {
    exec("node -v", (error, stdout, stderr) => {
      if (error) {
        console.error(`获取Node.js版本出错: ${error.message}`);
        if (retryCount > 0) {
          console.log(`重试次数剩余: ${retryCount}`);
          // 可以在这里进行一些清除操作或其他处理
          setTimeout(() => {
            getNodeVersion(retryCount - 1)
              .then(resolve)
              .catch(reject);
          }, 1000); // 延迟一秒后重试
        } else {
          reject("无法获取Node.js版本");
        }
      } else {
        const nodeVersion = stdout.trim().replace(/^v/, "");
        resolve(nodeVersion);
      }
    });
  });
}
getNodeVersion().then((res) => {
  console.log(res);
});
// 定义路由来获取目录下所有文件名
router.get("/listFiles", (req, res) => {
  const directoryPath = "C:/NodeVersionPackages";

  fs.readdir(directoryPath, (err, files) => {
    if (err) {
      console.error(err);
      res.status(500).json({ error: "无法读取目录内容" });
      return;
    }

    // 筛选出符合条件的文件名并提取版本号
    const filteredVersions = files
      .filter((file) => file.includes("node-v") && !file.includes(".zip"))
      .map((file) => file.match(/v(\d+\.\d+\.\d+)/)[1]);

    res.send({ versions: filteredVersions, code: 200, message: "获取成功" });
  });
});

// 下载路由
let downloadProgress = 0; // 全局变量用于保存下载进度

// 获取下载进度的函数
function getDownloadProgress() {
  return downloadProgress;
}

// 保存下载进度的函数
function saveDownloadProgress(progress) {
  downloadProgress = progress;
}

// 下载进度路由
router.get("/downloadProgress", (req, res) => {
  // 这里可以返回下载进度信息，比如从全局变量或其他地方获取
  const progress = getDownloadProgress(); // 获取下载进度的逻辑
  res.send({ progress });
});

// 下载逻辑路由
router.post("/downloadNode", async (req, res) => {
  const version = req.body.version;
  console.log(version);
  const targetFolder = path.resolve("C:/NodeVersionPackages");
  const filePath = path.join(targetFolder, `node-v${version}-win-x64.zip`);

  if (fs.existsSync(filePath)) {
    console.log(`Node.js 版本 ${version} 已存在于文件夹中`);
    res.json({ message: `Node.js 版本 ${version} 已存在于文件夹中` });
    return;
  }

  try {
    const response = await axios({
      method: "get",
      url: `https://nodejs.org/dist/v${version}/node-v${version}-win-x64.zip`,
      responseType: "stream",
    });

    if (!fs.existsSync(targetFolder)) {
      fs.mkdirSync(targetFolder, { recursive: true });
    }

    const writer = fs.createWriteStream(filePath);
    let downloadedBytes = 0;
    let totalBytes = parseInt(response.headers["content-length"], 10);

    response.data.on("data", (chunk) => {
      downloadedBytes += chunk.length;
      const progress = (downloadedBytes / totalBytes) * 100;
      // 保存下载进度到全局变量或其他地方
      saveDownloadProgress(progress);
      console.log(`Download Progress: ${progress.toFixed(2)}%`);
    });

    response.data.pipe(writer);

    writer.on("finish", () => {
      fs.createReadStream(filePath)
        .pipe(unzipper.Extract({ path: targetFolder }))
        .on("close", () => {
          console.log("文件解压完成");
          res.send({ code: 200, message: "Node.js 下载和解压缩完成" });
        })
        .on("error", (err) => {
          console.error(err);
          res.status(500).json({ error: "解压缩过程中发生错误" });
        });
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "文件下载过程中发生错误" });
  }
});

router.post("/switch-node-version", (req, res) => {
  let { version } = req.body;
  //   const version = "16.20.0"; // 从请求中获取输入的版本号
  const oldPaths = getOldPath(); // 假设该函数可以成功获取旧路径

  // 新路径
  const newPath = `C:\\NodeVersionPackages\\node-v${version}-win-x64`;

  // 读取批处理文件内容
  fs.readFile("范本 copy.bat", "utf8", (err, data) => {
    if (err) {
      console.error(err);
      res.status(500).send("读取文件时出错");
      return;
    }

    // 匹配并替换旧路径和新路径
    const oldPathPattern =
      /set "oldPath=C:\\NodeVersionPackages\\node-v\d+\.\d+\.\d+-win-x64"/;
    const newPathPattern =
      /set "newPath=C:\\NodeVersionPackages\\node-v\d+\.\d+\.\d+-win-x64"/;

    const updatedContent = data
      .replace(oldPathPattern, `set "oldPath=${oldPaths}"`)
      .replace(newPathPattern, `set "newPath=${newPath}"`);

    // 将替换后的内容写入批处理文件
    fs.writeFile("范本11.bat", updatedContent, "utf8", (err) => {
      if (err) {
        console.error(err);
        res.status(500).send("写入新文件时出错");
        return;
      }

      console.log("批处理文件已更新");
      //   res.send("批处理文件已更新");

      // 执行批处理文件
      exec("cmd /c 范本11.bat", (error, stdout, stderr) => {
        if (error) {
          console.error("Error running batch script:", error);
          return res
            .status(500)
            .json({ error: "Failed to switch Node.js version" });
        }

        console.log(`stdout: ${stdout}`);
        console.error(`stderr: ${stderr}`);

        // 执行 node -v 命令验证切换后的 Node.js 版本
        exec("node -v", (error, stdout, stderr) => {
          if (error) {
            console.error(error);
            return res
              .status(500)
              .json({ error: "Failed to switch Node.js version" });
          }
        });
      });
    });
  });
});

function getOldPath() {
  const paths = process.env.PATH.split(":");
  // 清理路径中的多余分隔符和';C'
  const cleanedPaths = paths.map((path) => path.replace(/;C$/, ""));
  const nodePaths = cleanedPaths.filter((path) => path.includes("node"));
  const absolutePaths = nodePaths.map((nodePath) => path.resolve(nodePath));
  console.log('包含 "node" 的路径：');
  console.log(absolutePaths);
  return Array.from(absolutePaths)[0];
}
const paths = process.env.PATH.split(":");
// 清理路径中的多余分隔符和';C'
const cleanedPaths = paths.map((path) => path.replace(/;C$/, ""));
const nodePaths = cleanedPaths.filter((path) => path.includes("node"));
const absolutePaths = nodePaths.map((nodePath) => path.resolve(nodePath));
console.log('包含 "node" 的路径：');
console.log(absolutePaths);
module.exports = router;
